package com.wct.springcloud.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.wct.springcloud.model.Dept;
import com.wct.springcloud.service.DeptService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author WEI (Email:changtan20000@163.com)
 * @description
 * @date: 2019/12/11 15:31
 */
@Slf4j
@RestController
public class DeptController {

    @Autowired
    private DeptService deptService;

    @Autowired
    private DiscoveryClient client;

    @PostMapping(value = "/dept/add")
    public boolean add(@RequestBody Dept dept) {
        log.info("/dept/add/ dept: {}", dept.toString());
        return deptService.add(dept);
    }

    // 一但调用服务方法并抛出异常后，会自动调用@HystrixCommand标注好的fallbackMethod调用类中的指定方法
//    @HystrixCommand(fallbackMethod = "processHystrix_Get")
    @GetMapping(value = "/dept/get/{deptno}")
    public Dept get(@PathVariable("deptno") Integer deptno) {
        Dept dept = deptService.get(deptno);
        log.info("dept: {}",dept);
        if (dept == null) {
            throw new RuntimeException("该ID: " + deptno + " 没有对应的信息");
        }
        return dept;
    }

    public Dept processHystrix_Get(@PathVariable("deptno") Integer deptno) {
        Dept dept = new Dept();
        dept.setDeptno(deptno);
        dept.setDname("该deptno: " + deptno + " 没有对应的信息，null--@HystrixCommand");
        dept.setDbSource("no this deptno data in MYSQL database");
        return dept;
    }

    @GetMapping(value = "/dept/list")
    public List<Dept> list() {
        log.info("/dept/list list: ");
        return deptService.list();
    }

    @GetMapping(value = "/dept/discovery")
    public Object discovery() {
        // 从eureka获取服务
        List<String> services = client.getServices();
        for (String s : services) {
            log.info("service: {}", s);
        }
        // 根据Application name获取微服务访问信息
        List<ServiceInstance> serviceInstances = client.getInstances("microservicecloud-dept-provider");
        for (ServiceInstance element : serviceInstances) {
            log.info("serviceId: {} \t host: {} \t url: {} \t port: {} \t instanceId: {}",
                    element.getServiceId(), element.getHost(), element.getUri(), element.getPort(), element.getInstanceId());
        }
        return this.client;
    }
}
